package com.monco.controller;

import com.monco.common.response.ApiResult;
import com.monco.entity.User;
import com.monco.service.IUserService;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author monco
 */
@Api(tags = "注册模块API")
@RestController
@RequestMapping("register")
public class RegisterController {

    @Autowired
    private IUserService userService;

    @PostMapping
    public ApiResult register(@RequestBody User user) {
        List<User> userList = userService.getUserList(new User().setUsername(user.getUsername()));
        if (CollectionUtils.isNotEmpty(userList)) {
            return ApiResult.error("该账号已经存在");
        }
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        String encodedPassword = new SimpleHash("md5", user.getPassword(), salt, 2).toString();
        user.setPassword(encodedPassword);
        user.setSalt(salt);
        userService.save(user);
        return ApiResult.ok();
    }
}
